import type { DirectiveBinding } from 'vue'
import { copyText } from '../../../utils/platform'

/**
 * @description demo
<template>
  <div v-copy="copyvalue">点击复制</div>
</template>

<script setup>
import { ref } from 'vue'
const copyvalue = ref('点击复制哈哈哈 ')
</script>
 */

/**
 * @description demo
<template>
  <div v-copy:[success]="copyvalue">点击复制</div>
</template>

<script setup>
import { ref } from 'vue'
const copyvalue = ref('点击复制哈哈哈 ')
const success = (val) => {
  console.log('内容是', val)
}
</script>
 */

const copy = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string | any>) {
    el.textContent = binding.value
    el.addEventListener('click', async () => {
      if (!el.textContent) return console.warn('没有需要复制的目标内容')
      await copyText(el.textContent)
      const success: (...arg: any) => void = binding.arg as unknown as () => void
      if (typeof success === 'function') {
        success(el.textContent)
      }
    })
  },
  updated(el: HTMLElement, binding: DirectiveBinding<string>) {
    // 实时更新最新的目标内容
    el.textContent = binding.value
  },
  unmounted(el: HTMLElement) {
    el.removeEventListener('click', () => { })
  }
}
export default copy
